package nckd.wnqjt.tmc.tda.plugin.form;

import kd.bos.algo.DataSet;
import kd.bos.algo.Row;
import kd.bos.dataentity.entity.LocaleString;
import kd.bos.entity.qing.*;
import kd.bos.form.IPageCache;
import kd.bos.form.plugin.AbstractFormPlugin;
import kd.bos.orm.query.QCP;
import kd.bos.orm.query.QFilter;
import kd.bos.servicehelper.QueryServiceHelper;

import java.sql.Timestamp;
import java.util.*;

import static nckd.wnqjt.tmc.tda.plugin.form.DateUtils.getNowMonthMinToDate;

/**
 * @Classname BankLoanBeginQingQueryPlugin
 * @Description 银行借款期初余额
 * @Version 1.0.0
 * @Date 2024/11/27 下午2:42
 * @Created by xiaoxiaopeng
 */
public class BankLoanBeginQingQueryPlugin extends AbstractFormPlugin implements IQingDataProvider {

    //银行贷款类型
    private final String[] loanType = {"loan","sl","bond"};

    @Override
    public QingMeta getMeta(String s) {
        String entityKey = "cfm_loanbill";
        QingMeta meta = new QingMeta();
        EntryEntity entity = new EntryEntity();
        entity.setKey(entityKey);
        entity.setName(new LocaleString("银行借款期初余额"));
        entity.setPkFieldName("id");
        meta.addEntryEntity(entity);

        Field column = new Field();
        /*column.setEntity(entityKey);//字段所属实体key	否
        column.setKey("id");// 字段名(唯一标识)	是
        column.setFieldType(QingFieldType.Int.toNumber()); //数据类型	是
        column.setName(new LocaleString("id")); //字段别名	是
        meta.addColumn(column);*/

        column = new Field();
        column.setEntity(entityKey);
        column.setKey("notrepayamount");
        column.setFieldType(QingFieldType.Number.toNumber());
        column.setName(new LocaleString("未还"));
        meta.addColumn(column);

        /*column = new Field();
        column.setEntity(entityKey);
        column.setKey("bizdate");
        column.setFieldType(QingFieldType.Date.toNumber());
        column.setName(new LocaleString("日期"));
        meta.addColumn(column);*/
        return meta;
    }

    @Override
    public QingData getData(String s, int startRow, int i1) {
        //拿过滤条件，进行取数
        String qFilter = getPageCache().get("qFilter");

        QFilter[] billFilters = null;
        //单据状态=审核
        QFilter qFilter1 = new QFilter("billstatus", QCP.equals,"C");
        //贷款类型=银行
        QFilter qFilter2 = new QFilter("loantype", QCP.in,loanType);
        //未还本金=0
        QFilter qFilter3 = new QFilter("notrepayamount", QCP.not_equals,0);

        billFilters = new QFilter[]{qFilter1, qFilter2,qFilter3};
        String loanField = "id,bizdate,billstatus,loantype,notrepayamount,drawamount";
        //期末余额
        DataSet loanDataSet = QueryServiceHelper.queryDataSet(this.getClass().getName(), "cfm_loanbill", loanField, billFilters, null);
        loanDataSet = loanDataSet.groupBy().sum("notrepayamount").finish().select("notrepayamount,0 as drawamount,0 as amount");

        //本月新增借款
        QFilter qFilter4 = new QFilter("bizdate", QCP.large_equals,getNowMonthMinToDate()).and(new QFilter("bizdate", QCP.less_equals,new Date()));
        billFilters = new QFilter[]{qFilter1, qFilter2,qFilter4};
        DataSet nowMonthAddDataSet = QueryServiceHelper.queryDataSet(this.getClass().getName(), "cfm_loanbill", loanField, billFilters, null);
        nowMonthAddDataSet = nowMonthAddDataSet.groupBy().sum("drawamount").finish().select("0 as notrepayamount,drawamount,0 as amount");

        //本月归还
        String repaymentField = "id,bizdate,billstatus,loantype,amount";
        DataSet nowMonthRepaymentDataSet = QueryServiceHelper.queryDataSet(this.getClass().getName(), "cfm_repaymentbill", repaymentField, billFilters, null);
        nowMonthRepaymentDataSet = nowMonthRepaymentDataSet.groupBy().sum("amount").finish().select("0 as notrepayamount, 0 as drawamount,amount");

        DataSet dataSet = loanDataSet.union(nowMonthAddDataSet).union(nowMonthRepaymentDataSet);
        dataSet = dataSet.groupBy().sum("notrepayamount").sum("drawamount").sum("amount").finish().select("notrepayamount,drawamount,amount");

        QingData data = null;
        if (startRow < 200) {
            data = new QingData();
            Map<String, Integer> dataindex = new HashMap<String, Integer>();
            dataindex.put("notrepayamount", 0);
            data.setDataindex(dataindex);

            List<Object[]> rows = new ArrayList<Object[]>();
            while (dataSet.hasNext()) {
                Row row = dataSet.next();
                Object[] obj = new Object[1];
                obj[0] = row.getBigDecimal("notrepayamount").add(row.getBigDecimal("amount")).subtract(row.getBigDecimal("drawamount"));
                rows.add(obj);
            }
            data.setRows(rows);
        }
        return data;
    }

    @Override
    public void setFilterParameter(String filterParameter) {
        IPageCache pageCache = getPageCache();
        pageCache.put("qFilter", filterParameter);

    }

    @Override
    public String getFilterParameter() {
        return getPageCache().get("qFilter");
    }

    /**
     * 获取动态表单联查信息
     *
     * @param pageId
     * @param ctrKey
     * @return
     */
   /* @Override
    public List<QingLinkageInfo> getLinkageInfo(String pageId, String ctrKey) {
        //return IQingDataProvider.super.getLinkageInfo(pageId, ctrKey);
        List<QingLinkageInfo> infos = new ArrayList<QingLinkageInfo>();
        QingLinkageInfo info = new QingLinkageInfo();
        Map<String, String> formKey = new HashMap<>();
        AppInfo appInfo = AppMetadataCache.getAppInfo("bei");
        String formId1 = this.getView().getFormShowParameter().getAppId();
        formKey.put("AppId", appInfo.getAppId()); //需要打开的表单所在应用的id
        String formId = this.getView().getFormShowParameter().getFormId();
        formKey.put("FormId", "nckd_loandetails"); //需要打开的表单的id
        formKey.put("System", "IERP");
        formKey.put("CtrKey", ctrKey);
        info.setFormKey(JsonUtil.encodeToString(formKey));
        info.setFormDisplayName("借款表");//联查到表单的显示名称
        info.setFormPrimaryKey("id");//联查到表单的主键
        infos.add(info);//可以添加多个QingLinkageInfo对象
        this.getView().getPageCache().put("qingViewControlKey", ctrKey);//必要语句!
        return infos;
    }
*/

    /**
     * <p>调用此接口，触发业务逻辑，具体业务联查实现此接口<p/>
     *
     * @param ids    轻分析得到动态表单需要联査的1d的集合
     * @param pageId
     * @param formId
     * @param appId
     */
    /*@Override
    public void fireLinkageInfo(List<String> ids, String pageId, String formId, String appId) {
        //IQingDataProvider.super.fireLinkageInfo(ids, pageId, formId, appId);
        *//*具体的表单打开逻辑，业务自己去实现
        ids:联查到的主键的值
        pageId:触发联査的页面的pageId，可用于找到触发联査的页面: FormView view = (FormView)Sessiomanager.getCurrent().getView(pageId)
        formId:联查到的表单的id
        appId:联查到的表单所在应用的Id
        *//*

        *//*注意: 如果需要使用芒穹的view.showForm 方式打开表单，需要添加以下代码*//*
        // 组装 FormShomParaneter(披照业务场景亲实现)
        ReportShowParameter reportShowParameter = new ReportShowParameter();
        reportShowParameter.getOpenStyle().setShowType(ShowType.Modal);
        reportShowParameter.setAppId(appId);
        reportShowParameter.setFormId(formId);//报表标识
        //拿过滤条件，进行取数
        String qFilter = getPageCache().get("qFilter"); //从仪表板进去 拿不到
        //通过此方法拿到过滤参数
        Map<String, Object> filterParam = new HashMap<>();
        // 设置报表过滤条件
        ReportQueryParam reportQueryParam = new ReportQueryParam();
        //FilterInfo filterInfo = new FilterInfo();
        //filterInfo.addFilterItem("nckd_orgview", filterParam.get("nckd_orgview"));
        //filterInfo.addFilterItem("nckd_org", filterParam.get("nckd_org"));
        //filterInfo.addFilterItem("nckd_currency", filterParam.get("nckd_currency"));
        //filterInfo.addFilterItem("bizdate", filterParam.get("nckd_querydate"));
        //filterInfo.addFilterItem("nckd_amountunit", filterParam.get("nckd_amountunit"));
        filterParam.put("id", ids);
        //reportQueryParam.setFilter(filterInfo);
        reportQueryParam.setCustomParam(filterParam);
        reportShowParameter.setQueryParam(reportQueryParam);

        *//*******************************showForm必要的代码******************************************//*
        IFormView view = SessionManager.getCurrent().getView(pageId);
        String ctrKey = this.getView().getPageCache().get("qingViewControlKey");
        if (ctrKey != null) {
            if (view.getControl(ctrKey) instanceof IQingAnalysis) {
                //设计器的场景，直接showForm
                view.showForm(reportShowParameter);
                return;
            }
        }
        //其他场景需要，返回FormShowParameter，由轻分析来 showForm
        this.getView().setClientReturnData(ListShowParameter.toJsonString(reportShowParameter));
        *//*******************************showForm必要的代码******************************************//*
    }*/
}
